package com.fly.office.word.tool;

import com.fly.office.constant.ChartEnum;
import com.fly.office.word.model.ChartModel;
import com.fly.office.word.util.PoiWordTools;
import com.fly.office.word.util.WordDynamicTool;
import org.apache.poi.ooxml.POIXMLDocumentPart;
import org.apache.poi.xwpf.usermodel.XWPFChart;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * word基础工具类
 *
 * @author lf
 */
public class WordTool {

    static Logger logger = LoggerFactory.getLogger(WordTool.class);

    /**
     * 生成图表
     * @param model
     */
    public static void generate(ChartModel model)
    {
        XWPFDocument doc = genDoc(model.getTplPath());
        if(doc!=null)
        {
            //读取模板中所有图表元素
            Map<String, POIXMLDocumentPart> chartsMap = getDocPart(doc);
            //初始化图表
            initDoc(chartsMap,model);
            //下载文档
            download(doc,model.getOutPath());
        }
    }

    /**
     * 构建doc文档
     * @param tplPath 模板路径
     * @return
     */
    public static XWPFDocument genDoc(String tplPath)
    {
        logger.info("模板路径：{}",tplPath);
        InputStream is = WordTool.class.getResourceAsStream(tplPath);
        XWPFDocument doc = null;
        try {
            doc = new XWPFDocument(is);
        } catch (IOException e) {
            logger.error("读取模板失败：{}",e);
        }
        return doc;
    }

    /**
     * 获取模板中所有图表元素
     * @param doc
     * @return
     */
    public static Map<String, POIXMLDocumentPart> getDocPart(XWPFDocument doc)
    {
        //获取word模板中的所有图表元素，用map存放
        Map<String, POIXMLDocumentPart> chartsMap = new HashMap<String, POIXMLDocumentPart>();
        //动态刷新图表
        List<POIXMLDocumentPart> relations = doc.getRelations();
        for (POIXMLDocumentPart poixmlDocumentPart : relations) {
            // 如果是图表元素
            if (poixmlDocumentPart instanceof XWPFChart) {

                // 获取图表对应的表格数据里面的第一行第一列数据，可以拿来当作key值
                String key = PoiWordTools.getZeroData(poixmlDocumentPart).trim();
                logger.info("图表对象值key：{}",key);

                chartsMap.put(key, poixmlDocumentPart);
            }
        }
        logger.info("图表数量：{}",chartsMap.size());
        return chartsMap;
    }

    /**
     * 初始化文档图表
     * @param chartsMap
     * @param model
     */
    public static void initDoc(Map<String, POIXMLDocumentPart> chartsMap, ChartModel model)
    {
        //图表对象key
        POIXMLDocumentPart poixmlDocumentPart = chartsMap.get(model.getKey());
        logger.info("图表模型：{}",model.getChartModel().getDesc());
        switch (model.getChartModel()){
            case CHART_COLUMNAR:
            case CHART_BAR:
                WordDynamicTool.replaceBarCharts(poixmlDocumentPart,model.getChartName(), model.getTitles(), model.getFields(), model.getDataList());
                break;
            case CHART_LINE:
                WordDynamicTool.replaceLineCharts(poixmlDocumentPart, model.getChartName(), model.getTitles(), model.getFields(), model.getDataList());
                break;
            case CHART_PIE:
                WordDynamicTool.replacePieCharts(poixmlDocumentPart, model.getChartName(), model.getTitles(), model.getFields(), model.getDataList());
                break;
            case CHART_RADAR:
                WordDynamicTool.replaceRadarCharts(poixmlDocumentPart, model.getChartName(), model.getTitles(), model.getFields(), model.getDataList());
                break;
            default:
                logger.error(ChartEnum.CHART_UNKNOWN.getDesc());
                break;
        }
    }

    /**
     * 下载文件
     * @param doc doc文档
     * @param outPath 下载路径
     */
    public static void download(XWPFDocument doc,String outPath)
    {
        // 保存结果文件
        FileOutputStream fos = null;
        try {
            File file = new File(outPath);
            if (file.exists()) {
                file.delete();
            }
            fos = new FileOutputStream(outPath);
            doc.write(fos);
            logger.info("生产文档成功！");
        } catch (Exception e) {
            logger.error("文档输出异常：{}",e);
        }finally {
            if(fos!=null)
            {
                try {
                    fos.close();
                } catch (IOException e) {
                    logger.error("系统异常：{}",e);
                }
            }
        }
    }

}
